import { MutationTree } from "vuex";
import { ProfileState } from "../types";
import {
    SAVE_GEOHASH,// 保存经纬度
    SAVE_POIS, //记录当前位置的名称
    RECORD_USERINFO, // 记录登陆信息
    SAVE_USERIMG,   //记录用户头像
    ADD_CART,   //加入购物车
    REDUCE_CART,    //移除购物车
} from './mutation-types'
import {setStore} from "@/utils/utils";
import {toNumber} from "lodash";
export const mutations: MutationTree<ProfileState> = {
    [SAVE_GEOHASH](state, geohash) {
        state.geohash = geohash;
    },
    [SAVE_POIS](state, pois) {
        state.pois = pois;
    },
    // 记录用户信息
    [RECORD_USERINFO](state, info) {
        state.userInfo = info;
        state.login = true;
        setStore('user_id', info.user_id);
    },
    [SAVE_USERIMG](state,path){
        state.imgPath = '//elm.cangdu.org/img/' + path;
    },
    // 加入购物车
    [ADD_CART](state, {
        restaurant_id, //商铺的ID
        category_id,    //分类ID
        item_id,
        food_id,    //食物ID
        food_img,   //食物照片
        name,   //名称
        price,  //价格
        specs,  //数量
        packing_fee,    //打包费
        sku_id,
        stock,
    }) {
        let cart = state.cartList;  //拿到之前的购物车列表
        let shop = cart[restaurant_id] = (cart[restaurant_id] || {});
        let category = shop[category_id] = (shop[category_id] || {});
        let item = category[item_id] = (category[item_id] || {});
        if (item[food_id]) {
            item[food_id]['num']++;
        } else {
            item[food_id] = {
                "num" : 1,
                "id" : food_id,
                "img" : food_img,
                "name" : name,
                "price" : price,
                "specs" : specs,
                "packing_fee" : packing_fee,
                "sku_id" : sku_id,
                "stock" : stock
            };
        }
        state.cartList = {...cart};
        //存入localStorage
        setStore('buyCart', JSON.stringify(state.cartList));
    },
    // 移出购物车
    [REDUCE_CART](state, {restaurant_id,category_id,item_id,food_id,}) {
        let cart = state.cartList;
        let shop = (cart[restaurant_id] || {});
        let category = (shop[category_id ] || {});
        let item = (category[item_id] || {});
        if (item && item[food_id]) {
            if (item[food_id]['num'] > 1) {
                item[food_id]['num']--;
                state.cartList = {...cart};
                //存入localStorage
                setStore('buyCart', JSON.stringify(state.cartList));
            } else {
                //商品数量为0，则清空当前商品的信息
                item[food_id] = null;
            }
        }
    },
};

